import resources.Constants;

import registnet.dao.SectionConfigurationPeer;
import registnet.dao.SectionConfiguration;
import registnet.dao.UnitPeer;

registnet.dao.SystemPropertiesPeer spp = new registnet.dao.SystemPropertiesPeer();

String _add = bundle.getProperty("registnet.module.data_management.actions.menu.add");
String _edit = bundle.getProperty("registnet.module.data_management.actions.menu.edit");
String _delete = bundle.getProperty("registnet.module.data_management.actions.menu.delete");
String _save = bundle.getProperty("registnet.module.data_management.macro.colleges.form.save");
String _cancel = bundle.getProperty("registnet.module.data_management.macro.colleges.form.cancel");

SectionConfigurationPeer scp = new SectionConfigurationPeer();
SectionConfiguration sc = new SectionConfiguration();

String _icon_add = bundle.getProperty("registnet.icons.add");
String _icon_edit = bundle.getProperty("registnet.icons.edit");
String _icon_delete = bundle.getProperty("registnet.icons.delete");
String _icon_configure = bundle.getProperty("registnet.icons.configure");
String _icon_refresh = bundle.getProperty("registnet.icons.show_all");
String _icon_red = bundle.getProperty("registnet.icons.red");
String _icon_green = bundle.getProperty("registnet.icons.green");
String _icon_yellow = bundle.getProperty("registnet.icons.yellow");

List data = new Vector();


boolean isShowingInfo;


/* [start]	prepares the tree */
ArrayList alc = new ArrayList();
SimpleTreeNode root = new SimpleTreeNode("ROOT", alc);
/* [end] */


/* [start]	defines the renderer for the tree */
public class MyTreeitemRenderer implements TreeitemRenderer {
	public void render(Treeitem item, Object data) throws Exception {
		String str = (String)data.getData();
		Treerow tr = null;
		Treecell tc = new Treecell(str);
		if(item.getTreerow()==null){
			tr = new Treerow();
			tr.setParent(item);
		}else{
			tr = item.getTreerow(); 
			tr.getChildren().clear();
		}
		tc.setParent(tr);
		item.setOpen(false);
	}
}
/* [end] */


/* [start]	retrieves the section configurations and places them on the tree; */
public void retrieveObjects(){
	alc.clear();
	data = scp.getAllSectionConfigurationsByUnit(new UnitPeer().getUnitId(_office));
	for(int i=0; i<data.size(); i++){
		SimpleTreeNode stnSectionConfiguration = new SimpleTreeNode(data.get(i).getSectionConfigurationName(), new ArrayList());
		alc.add(stnSectionConfiguration);
	}
	SimpleTreeModel stm = new SimpleTreeModel(root);
	instance_tree.setModel(stm);
	instance_tree.setTreeitemRenderer(new MyTreeitemRenderer());
}
/* [end] */


/* [start]	defines an event listener for the items on the tree;
			when the item is selected, its info is displayed */
private class SelectEventListener implements EventListener {
	public SelectEventListener (){}
	public void onEvent(Event event) throws UiException {
		showSectionConfigurationDetails();
	}
}
/* [end] */


/* [start]	defines an event listener for the cancel button;
			when fired, it deselects the items on the tree */
private class CancelEventListener implements EventListener {
	public SubmitEventListener (){}
	public void onEvent(Event event) throws UiException {
		instance_tree.clearSelection();
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}
/* [end] */


/* [start]	defines an event listener for the submit button */
private class SubmitEventListener implements EventListener {
	String submitType;
	public SubmitEventListener (String submitType){
		this.submitType = submitType; 
	}
	public void onEvent(Event event) throws UiException {
		if(this.submitType.equals(_add))
			createNewSectionConfiguration();
		else if (this.submitType.equals(_edit))
			editSectionConfiguration();
	}
}
/* [end] */


void showInfo(){
	isShowingInfo = true;
	if (contents.getFirstChild() != null){
		contents.removeChild(contents.getFirstChild());
	}
	
	try{
		if (instance_tree.getSelectedCount() == 1){
			sc = scp.getSectionConfiguration(new UnitPeer().getUnitId(_office), instance_tree.getSelectedItem().getLabel());
			Component show_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_form.zul", contents, null);
			title.setValue(sc.getSectionConfigurationName());
			show_instance_form.getFellow("configuration_name_l").setValue(sc.getSectionConfigurationName());
			show_instance_form.getFellow("save_btn").detach();
			show_instance_form.getFellow("cancel_btn").detach();
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + "Section Configuration" + " " + "selected");
		else
			title.setValue("");
	}catch (Exception e) { title.setValue(""); }
}


/* [start]	displays the form for creating a new or editing an existing entry */
void showForm(String action){
	isShowingInfo = false;
	try{
		contents.removeChild(contents.getFirstChild());
	} catch (Exception e) {}
	if (action.equals(_edit)){
		if(instance_tree.getSelectedCount() == 1){
			Component edit_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_form.zul", contents, null);
			title.setValue(_edit + " " + sc.getSectionConfigurationName());
			edit_instance_form.getFellow("configuration_name").setValue(sc.getSectionConfigurationName());
			edit_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
			edit_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
		}
		else{
			alert("Select one Section Configuration");
		}
	}	
	else if (action.equals(_add)){
		Component add_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_form.zul", contents, null);
		title.setValue(_add + " " + "Section Configuration");
		instance_tree.clearSelection();
		add_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
		add_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
	}
}
/* [end] */



/* [start]	creates a new entry;
			updates the tree */
void createNewSectionConfiguration(){
	if (isValid()){
		if (scp.createNewSectionConfiguration(new UnitPeer().getUnitId(_office), configuration_name.value) != null){
			data.add(scp.getSectionConfiguration(new UnitPeer().getUnitId(_office), configuration_name.value));
			title.setValue("Add Section Configuration Successful");
			SimpleTreeNode stnConfiguration = new SimpleTreeNode(configuration_name.value, new ArrayList());
			alc.add(stnConfiguration);
			instance_tree.setModel(instance_tree.getModel());		
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		}
		else
			alert("Check information supplied");
	}
	else{
		alert("Check information supplied");
	}
}
/* [end] */



/* [start]	edits an existing entry;
			updates the tree */
void editSectionConfiguration(){
	if (isValid()){
		try{
			if (scp.updateSectionConfiguration(sc.getSectionConfigurationId(), configuration_name.value)){
				data.set(instance_tree.getSelectedItem().indexOf(), scp.getSectionConfiguration(new UnitPeer().getUnitId(_office), configuration_name.value));
				SimpleTreeNode stnConfiguration = new SimpleTreeNode(configuration_name.value, new ArrayList());
				alc.set(instance_tree.getSelectedItem().indexOf(), stnConfiguration);
				instance_tree.clearSelection();
				instance_tree.setModel(instance_tree.getModel());
				title.setValue("Edit Section Configuration Successful");
			}
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		} catch (Exception e) { alert("Check information supplied"); }
	}
	else{
		alert("Check information supplied");
	}
}
/* [end] */



/* [start]	deletes an entry */
void delete(){
	if(instance_tree.getSelectedCount() != 0){
		int isConfirmed = Messagebox.show("Proceed", "Delete" + " " + "Section Configuration", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
		if (isConfirmed == Messagebox.YES){
			boolean isError = false;
			int errorCount = 0;
			Iterator i = instance_tree.getSelectedItems().iterator();
			int counter = 0;
			while(i.hasNext()){
				Treeitem treeitem = i.next(); 
				if (scp.deleteSectionConfiguration(new UnitPeer().getUnitId(_office), treeitem.getLabel())){
					alc.remove(treeitem.indexOf() - counter);
					data.remove(treeitem.indexOf() - counter);
					counter++;
				}
				else{
					isError = true;
					errorCount++;
				}				
			}
			instance_tree.setModel(instance_tree.getModel());
			if (isError){ 
				alert("Delete" + " " + "failed" + ": " + errorCount + " " + "Section Configuration");
				title.setValue("Delete" + " " + "Section Configuration" + " " + "failed");
			}
			
			else{
				title.setValue("Delete" + " " + "Section Configuration" + " " + "successful");
				if (contents.getFirstChild() != null){
					contents.removeChild(contents.getFirstChild());
				}
			}
		}			
	}
	else{
		alert("Select one Section Configuration");
	}
}
/* [end] */



boolean isValid(){
	if (configuration_name.value.trim().length() == 0)
		return false;
	return true;
}


void configure(){
	try{
		if (instance_tree.getSelectedCount() == 1){
			sc = scp.getSectionConfiguration(new UnitPeer().getUnitId(_office), instance_tree.getSelectedItem().getLabel());
			
			
			if(!map_tab.containsKey(sc.getSectionConfigurationName())){
			
				Tabbox stage = section_configuration_win.getParent().getParent().getParent();
				
				Tabs tabs = stage.getTabs();
				Tab tab = new Tab(sc.getSectionConfigurationName());
				tab.setClosable(true);
				tab.setParent(tabs);
				tab.addEventListener("onClose", new CloseTabEventListener(sc.getSectionConfigurationName()));
				
				Tabpanels tabpanels = stage.getTabpanels();
				Tabpanel tabpanel = new Tabpanel();
				tabpanel.setSclass("background_light_blue");
				tabpanel.setParent(tabpanels);
				stage.setSelectedPanel(tabpanel);
				
				map_tab.put(sc.getSectionConfigurationName(), tab);
				
				HashMap map = new HashMap();
				map.put("configId", sc.getSectionConfigurationId());
				Component win = Executions.createComponents("../../WEB-INF/macros/data_management/configuration_sections.zul", tabpanel, map);
			}
			
			else
				map_tab.get(sc.getSectionConfigurationName()).setSelected(true);
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + "Section Configuration" + " " + "selected");
		else
			title.setValue("");
	}catch (Exception e) { e.printStackTrace(); title.setValue(""); }
}

showSectionConfigurationDetails(){
	isShowingInfo = true;
	title.setValue(instance_tree.getSelectedItem().getLabel()+" Configuration");
	if (contents.getFirstChild() != null){
		contents.removeChild(contents.getFirstChild());
	}
	boolean left=true;
	boolean hasSections=false;
	try{
		if (instance_tree.getSelectedCount() == 1){
			Component view_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_view_form.zul", contents, null);
			Rows rows = new Rows();
			int configId = scp.getSectionConfiguration(new UnitPeer().getUnitId(_office),instance_tree.getSelectedItem().getLabel()).getSectionConfigurationId();
			List courses = new CoursePeer().getCoursesByUnit(new UnitPeer().getUnitId(_office));
			for(int i=0; i<courses.size(); i++){
				
					
				List lect = new SectionPeer().getLectureSections(courses.get(i).getCourseId(),configId);
				if(lect.size()<=0)
					continue;
				else
					hasSections=true;
				if(left){
					rows = view_form.getFellow("rowsL");
					left=false;
				}
				else{
					rows = view_form.getFellow("rowsR");
					left=true;
				}
				int availableSlots = 0;
				int lackingSlots = 0;
				int demandSlots = new registnet.dao.CourseDemandPeer().getCourseDemand(courses.get(i).getCourseId()).getEstimatedDemand();;
				Group course = new Group();
				Hbox hb = new Hbox();
				Hbox hb1 = new Hbox();
				Hbox hb2 = new Hbox();
				Hbox hb3 = new Hbox();
				hb.setSpacing("15px");
				Image green = new Image(_icon_green);
				Image yellow = new Image(_icon_yellow);
				Image red = new Image(_icon_red);
				Label code = new Label(courses.get(i).getCourseCode());
				code.setParent(hb);
				
				Label slots = new Label();
				Label lack = new Label();
				Label demand = new Label();
				slots.setStyle("color:black");
				lack.setStyle("color:black");
				demand.setStyle("color:black");
				
				green.setWidth("12px");
				green.setHeight("12x");
				yellow.setWidth("12px");
				yellow.setHeight("12x");
				red.setHeight("12x");
				red.setWidth("12px");
				
				green.setParent(hb1);
				slots.setParent(hb1);
				red.setParent(hb2);
				lack.setParent(hb2);
				yellow.setParent(hb3);
				demand.setParent(hb3);
				
				hb1.setParent(hb);
				hb2.setParent(hb);
				hb3.setParent(hb);
				
				hb.setParent(course);
				//course.setLabel(courses.get(i).getCourseCode());
				course.setParent(rows);
				
				Row r = new Row();
				Separator sp = new Separator();
				sp.setWidth("5px");
				sp.setParent(r);
				
				Grid g = new Grid();
				Rows rws = new Rows();
				rws.setParent(g);
				g.setStyle("border-left:0");
				Columns c = new Columns();
				Column cl1 = new Column();
				Column cl2 = new Column();
				Column cl3 = new Column();
				cl1.setParent(c);
				cl2.setParent(c);
				cl3.setParent(c);
				cl1.setWidth("30%");
				cl2.setWidth("35%");
				cl3.setWidth("35%");
				c.setParent(g);
				
				g.setParent(r);
				r.setParent(rows);
				for(int j=0; j<lect.size(); j++){
					Row rw = new Row();
					rw.setStyle("border:none");
					Label l1 = new Label();
					Label l2 = new Label();
					Label l3 = new Label();
					l1.setValue(lect.get(j).getSectionName());
					l2.setValue(lect.get(j).getLectureTime());
					l3.setValue(lect.get(j).getLectureDay());
					l1.setParent(rw);
					l2.setParent(rw);
					l3.setParent(rw);
					rw.setParent(rws);
					List labs = new SectionPeer().getLaboratory(configId, courses.get(i).getCourseId(),lect.get(j).getSectionName());
					if(labs.size==0 || labs==null){
						if(lect.get(j).getStudentCount()!=null)
							availableSlots+=lect.get(j).getStudentCount();
					}
					for(int k=0; k<labs.size(); k++){
						Row rw1 = new Row();
						rw1.setStyle("border:none");
						Label la1 = new Label();
						Label la2 = new Label();
						Label la3 = new Label();
						la1.setValue(labs.get(k).getSectionName());
						if(labs.get(k).getLaboratoryDay()!=null){
							la2.setValue(labs.get(k).getLaboratoryTime());
							la3.setValue(labs.get(k).getLaboratoryDay());
						}
						else{
							la2.setValue(labs.get(k).getRecitationTime());
							la3.setValue(labs.get(k).getRecitationDay());
						}
						if(labs.get(k).getStudentCount()!=null)
							availableSlots+=labs.get(k).getStudentCount();
						la1.setParent(rw1);
						la2.setParent(rw1);
						la3.setParent(rw1);
						rw1.setParent(rws);
					}
				}
				lackingSlots=demandSlots-availableSlots;
				if(lackingSlots>=0)
					lack.setValue(lackingSlots+"");
				else
					lack.setValue("0");
				slots.setValue(availableSlots+"");
				demand.setValue(demandSlots+"");
			}
			if(!hasSections){
				view_form.getFellow("error").setVisible(true);
			}
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + "Section Configuration" + " " + "selected");
		else
			title.setValue("");
	}catch (Exception e) { e.printStackTrace(); title.setValue(""); }
}

void finalize(){
	int configId = scp.getSectionConfiguration(new UnitPeer().getUnitId(_office),instance_tree.getSelectedItem().getLabel()).getSectionConfigurationId();
	boolean hasError=false;
	CourseOfferingPeer courseOfferingPeer = new CourseOfferingPeer();
	List sections = new SectionPeer().getSectionsBySectionConfiguration(configId);
	int sem ,year;
	if(spp.getSystemProperties().getSemester()>=2){
		year = spp.getSystemProperties().getAcademicYear()+1;
	}
	else
		year = spp.getSystemProperties().getAcademicYear();
	sem = (spp.getSystemProperties().getSemester()%3)+1;
		
	for(int i=0; i<sections.size(); i++){
		if(courseOfferingPeer.getCourseOfferingsByCourse(sections.get(i).getCourseId(), sem, year).size()>0){
			alert("Sections are already finalized.");
			return;
		}
	}
	
	if(sections.size()>0){
		for(int i=0; i<sections.size(); i++){
			if(courseOfferingPeer.createNewCourseOffering(sections.get(i).getCourseId(), sections.get(i).getSectionName(), sem, year, sections.get(i).getLaboratoryDay(), sections.get(i).getLectureDay(),sections.get(i).getRecitationDay(), sections.get(i).getLaboratoryRoom(), sections.get(i).getLectureRoom(), sections.get(i).getRecitationRoom(), sections.get(i).getLaboratoryTime(), sections.get(i).getLectureTime(), sections.get(i).getRecitationTime(), sections.get(i).getLaboratoryInstructor(), sections.get(i).getLectureInstructor(), sections.get(i).getRecitationInstructor(), sections.get(i).getIsTeamTeach(), sections.get(i).getStudentCount()) == null){
				alert("Failed to finalize "+new CoursePeer().getCourse(sections.get(i).getCourseId()).getCourseCode()+" "+sections.get(i).getSectionName());
			}
		}
		try{
			contents.removeChild(contents.getFirstChild());
		}catch(Exception e){}
		title.setValue("Sections successfully finalized using "+ scp.getSectionConfiguration(configId).getSectionConfigurationName()+ " configuration.");
		instance_tree.clearSelection();
	}
	else
		alert("No sections yet.");
}